package imv3.foo.server.handler;

import imv3.protocol.request.ListGroupMemberRequestPacket;
import imv3.protocol.response.ListGroupMemberResponsePacket;
import imv3.protocol.session.Session;
import imv3.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/26 0026 10:50
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
@ChannelHandler.Sharable
public class ListGroupMemberRequestHandler extends SimpleChannelInboundHandler<ListGroupMemberRequestPacket> {

    public static final ListGroupMemberRequestHandler INSTANCE = new ListGroupMemberRequestHandler();

    private ListGroupMemberRequestHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ListGroupMemberRequestPacket listGroupMemberRequestPacket) throws Exception {

        String groupId = listGroupMemberRequestPacket.getGroupId();
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);

        // 3. 构建获取成员列表响应写回到客户端
        ListGroupMemberResponsePacket responsePacket = new ListGroupMemberResponsePacket();
        responsePacket.setGroupId(groupId);

        if (channelGroup != null) {
            List<Session> sessionList = new ArrayList<>();
            responsePacket.setSuccess(true);
            for (Channel ch : channelGroup) {
                Session session = SessionUtil.getSession(ch);
                sessionList.add(session);
            }
            responsePacket.setSessionList(sessionList);
        } else {
            responsePacket.setSuccess(false);
            responsePacket.setReason("群聊[" + groupId + "]不存在");
        }

        ctx.channel().writeAndFlush(responsePacket);
    }
}
